package world2d;
import data.GlobalData;

import motion.Actuate;
import openfl.display.Bitmap;
import openfl.display.BitmapData;
import openfl.display.Sprite;
import openfl.events.KeyboardEvent;
import openfl.events.MouseEvent;

/**
 * ...
 * @author ...
 */
class Cannon extends Sprite
{
	private var  m_nRotation:Int;//360°, hexadecimal
	private var m_cBullet:Bullet2D;
	private var m_nSpeed:Int;

	public function new(cBullet:Bullet2D) 
	{
		super();
		m_cBullet = cBullet;
		m_nRotation = 0;
		m_nSpeed = 1000;
		var graph:Bitmap = new Bitmap(new BitmapData(50, 10, true, 0xff444444));
		this.addChild(graph);
		GlobalData.m_cMainCanvas.stage.addEventListener(KeyboardEvent.KEY_UP, readKey);
	
	}
	
	public function setDirection(nKte:Int):Void
	{
		m_cBullet.m_cKteDir = nKte;
		this.scaleX = nKte;
		}
	private function readKey(ev:KeyboardEvent)
	{
		trace("key code :" + ev.keyCode);
		
		switch (ev.keyCode)
		{
			case 32://space bar
				processSpaceBar();
				
			case 38: //key up
				processKeyUp();
				
			case 40:// key down
				processKeyDown();
 
		}
	}
	
	private function processKeyUp():Void
	{
		m_nRotation -= 2;
		Actuate.tween(this, 0.25, { rotation: m_nRotation*m_cBullet.m_cKteDir } ).smartRotation();
	}
	
	private function processKeyDown()
	{
		m_nRotation += 2;
		Actuate.tween(this, 0.25, { rotation: m_nRotation*m_cBullet.m_cKteDir } ).smartRotation();
	}
	private function processSpaceBar():Void
	{
		var nX:Float = Math.cos(m_nRotation * Math.PI / 180) * this.width + this.x;
		if (m_cBullet.m_cKteDir < 0)
			nX =  this.x - Math.cos(m_nRotation * Math.PI / 180 ) * this.width ;	
		var nY:Float = Math.sin(m_nRotation * Math.PI / 180) * this.width + this.y;
		var nSpeedX:Float = m_nSpeed * Math.cos(m_nRotation * Math.PI / 180) * m_cBullet.m_cKteDir  ;
		var nSpeedY:Float = m_nSpeed * Math.sin(m_nRotation * Math.PI / 180);
		m_cBullet.startMoving(nX, nY, nSpeedX, nSpeedY);
	}
}

